<template>
  <div>
    <div class="margin-top-div-8 body-content">
      <span class="margin-top-div-16 paragraph-p2-light">
        商品描述
        <span class="margin-left-4 color-red">*</span>
      </span>
      <field-textarea ref="productDescTextarea"
                      :value="product.productDesc"
                      :limit-count="500"
                      :placeholder="placeholder.productDesc"
      ></field-textarea>
    </div>

    <div class="margin-top-div-16 body-content">
      <div>
        <span class="margin-top-div-16 paragraph-p2-light">商品照片</span>
      </div>
      <div>
        <span class="color-grey tiny-light">
          最多支持9张照片；首图上传后会自动添加水印
        </span>
      </div>
    </div>
    <field-uploader class="margin-top-div-8" ref="prodPicUploaderRef"
                    :picture-list="product.productPictures"
                    :picture-id-list="product.productPictureIds"></field-uploader>

    <div class="collSpan-div paragraph-p2-heavy margin-top-div-8" @click="ifShowDetail = !ifShowDetail">
      <span> 商品属性 </span>
      <img v-if="ifShowDetail" class="icon-16" src="@/static/icon/arrow-up.png" alt=""/>
      <img v-if="!ifShowDetail" class="icon-16" src="@/static/icon/arrow-down.png" alt=""/>
    </div>
    <div v-if="ifShowDetail">
      <div class="margin-top-div-8 body-content">
        <!-- 货号 -->
        <van-field class="field-cell paragraph-p2-light"
            v-model="product.productNo"
            readonly
            label="货号"
            placeholder="213436435234324"
            input-align="right"
        ></van-field>
        <field-divider></field-divider>
        <!-- 分类 -->
        <van-field class="field-cell paragraph-p2-light"
            v-model="product.category"
            label="分类"
            placeholder="请选择"
            input-align="right"
            readonly
            is-link
            @click="ifShowCategory = !ifShowCategory"
        ></van-field>
        <van-action-sheet
            v-model="ifShowCategory"
            close-on-click-action
            cancel-text="取消"
        >
          <div class="body-content">
            <van-cell title="自购" @click="chooseCategory(1)">
              <!-- 使用 right-icon 插槽来自定义右侧图标 -->
              <template #right-icon>
                <img
                    v-if="category.selfPurchase"
                    class="icon-24"
                    src="@/static/icon/radio/20px_todo_checked.png" alt=""
                />
              </template>
            </van-cell>
            <van-cell title="寄卖" @click="chooseCategory(2)">
              <!-- 使用 right-icon 插槽来自定义右侧图标 -->
              <template #right-icon>
                <img
                    v-if="category.consignment"
                    class="icon-24"
                    src="@/static/icon/radio/20px_todo_checked.png" alt=""
                />
              </template>
            </van-cell>
          </div>
        </van-action-sheet>
        <field-divider></field-divider>
        <!-- 备注 -->
        <span class="margin-top-div-16 paragraph-p2-light">备注</span>
        <field-textarea ref="remarkTextarea" :limit-count="500" :placeholder="placeholder.remark"></field-textarea>
        <field-divider></field-divider>
        <!-- 尺寸 -->
        <van-field class="field-cell paragraph-p2-light"
                   label="尺寸"
                   :placeholder="product.productSize.length > 0 ? product.productSize.length === 1 && product.productSize[0] ==='' ? '请添加' : '' : '请添加' "
                   input-align="right"
                   readonly
                   is-link
                   @click="productSizeHandler"
        >
          <template #button v-if="product.productSize.length > 0">
            <template v-for="(item, i) in product.productSize">
              <van-tag type="primary" size="medium" color="#FFF5CC" text-color="#424242" style="margin-left: 4px"
                       v-if="item && item !== '' " :key="'productSizeTag' + i">{{ item }}
              </van-tag>
            </template>
          </template>
        </van-field>
        <van-action-sheet v-model="ifShowProductSize">
          <product-select
              :type=1
              :is-single-choice="true"
              :chooseItems="product.productSize"
              :quickChooseItems="sizePop.quickChooseItemList"
              v-on:productSelectBackEvent="productSelectBack"
              v-on:confirmEvent="productSizeConfirm"
          ></product-select>
        </van-action-sheet>
        <field-divider></field-divider>
        <!-- 配件 -->
        <!--
        <van-field class="field-cell paragraph-p2-light"
            label="配件"
            :placeholder="product.productFitting.length > 0 ? product.productFitting.length === 1 && product.productFitting[0] ==='' ? '请添加' : '' : '请添加' "
            input-align="right"
            readonly
            is-link
            @click="productFittingHandler"
        >
          <template #button v-if="product.productFitting.length > 0">
            <template v-for="(item, i) in product.productFitting">
              <van-tag type="primary" size="medium" color="#FFF5CC" text-color="#424242" style="margin-left: 4px"
                       v-if="item && item !== ''" :key="'productFittingTag' + i">{{ item }}
              </van-tag>
            </template>
          </template>
        </van-field>
        <van-action-sheet v-model="ifShowProductFitting">
          <product-select
              :type=2
              :chooseItems="product.productFitting"
              :quickChooseItems="fillPop.quickChooseItemList"
              v-on:productSelectBackEvent="productSelectBack"
              v-on:confirmEvent="productFittingConfirm"
          ></product-select>
        </van-action-sheet>
        <field-divider></field-divider>
        -->
        <!-- 数量 -->
        <!--
        <van-field class="field-cell paragraph-p2-light"
            v-model="product.productNum"
            label="数量"
            placeholder="1个"
            input-align="right"
            readonly
            is-link
            @click="ifShowProductNum = !ifShowProductNum"
        ></van-field>
        <van-popup v-model="ifShowProductNum" round position="bottom">
          <van-picker
              show-toolbar
              :columns="$route.params.id ? productNumEditColumns : productNumAddColumns"
              @confirm="productNumConfirm"
              @cancel="ifShowProductNum = false"
          />
        </van-popup>
        <field-divider></field-divider>
        -->
        <field-divider></field-divider>
        <!-- 成本价 -->
        <van-field class="field-cell paragraph-p2-light"
            v-model="product.costPrice"
            label="成本价(¥)"
            type="number"
            :placeholder="product.costPrice ? product.costPrice : '请输入成本价(人民币)'"
            input-align="right"
            :formatter="formatter" @blur="window.scroll(0,0)" @focus="window.scroll(70,0)"
        ></van-field>
        <field-divider></field-divider>
        <!-- 销售价 -->
        <van-field class="field-cell paragraph-p2-light"
            v-model="product.salePrice"
            label="销售价(¥)"
            type="number"
            :placeholder="product.salePrice ? product.salePrice : '请输入销售价(人民币)'"
            input-align="right"
            :formatter="formatter" @blur="window.scroll(0,0)" @focus="window.scroll(70,0)"
        ></van-field>
        <field-divider></field-divider>
        <!-- 零售价 -->
        <van-field class="field-cell paragraph-p2-light"
            v-model="product.retailPrice"
            label="零售价($)"
            type="number"
            :placeholder="product.retailPrice ? product.retailPrice : '请输入零售价(澳币)'"
            input-align="right"
            :formatter="formatter" @blur="window.scroll(0,0)" @focus="window.scroll(70,0)"
        ></van-field>
      </div>

      <div class="margin-top-div-16 margin-bottom-div-16" :class="product.id ? '' : 'last-div'">
        <div>
          <span class="body-content margin-top-div-16 paragraph-p2-light">附件</span>
        </div>
        <div>
          <span class="body-content margin-top-div-16-small tiny-light">
            最多支持9张照片+1个视频
          </span>
        </div>
        <field-uploader class="margin-top-div-8" :type="2" ref="prodAttachUploaderRef"
                        :class="product.attachmentPictureIds.length === 0 ? 'margin-left-16' : ''"
                        :picture-list="product.attachmentPictures"
                        :picture-id-list="product.attachmentPictureIds"></field-uploader>
      </div>

      <div class="del-div paragraph-p2-light margin-top-div-8" v-if="product.id"
           :class="listItemCode === productListItemType.toStorage ? 'last-div' : ''"
           @click="delProduct(product.id)">
        <img class="icon-16" src="@/static/icon/red-delete.png" alt=""/>
        <span>删除此商品</span>
      </div>
    </div>
    <button-center v-if="!product.id && listItemCode === productListItemType.toStorage"
                   :button-name="buttonName.toStorage" @click.native="addProduct"></button-center>
    <button-center v-if="!product.id && listItemCode === productListItemType.storage"
                   :button-name="buttonName.storage" @click.native="addProduct"></button-center>
    <button-center v-if="product.id && listItemCode === productListItemType.toStorage"
                   :button-name="buttonName.storage" @click.native="buttonStorage"></button-center>
  </div>
</template>
<script>
import {
  ActionSheet,
  Badge,
  Button,
  Cell,
  CellGroup,
  Divider,
  Field,
  Grid,
  GridItem,
  Popup,
  Radio,
  RadioGroup,
  Tag,
  Toast,
  Uploader,
} from "vant"
import ProductSelect from "@/components/product/select"
import ButtonCenter from "@/components/Button/Center"
import FieldTextarea from '@/components/Field/Textarea'
import FieldUploader from '@/components/Field/Uploader'
import FieldDivider from '@/components/Field/Divider'
import {
  changeProductStatus,
  createProduct,
  deleteProduct,
  editProduct,
  getProductCode,
  getUserAccesories,
  getUserSizes,
  viewProductDetail
} from "@/request/api";

export default {
  name: "ProductEdit",
  props: {
    listItemCode: {type: Number, default: () => (this.GLOBAL.listItemType.product.toStorage)},
    productItem: {type: Object, default: () => ({})},
  },
  components: {
    [Button.name]: Button,
    [Popup.name]: Popup,
    [Divider.name]: Divider,
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Cell.name]: Cell,
    [Grid.name]: Grid,
    [GridItem.name]: GridItem,
    [ActionSheet.name]: ActionSheet,
    [Tag.name]: Tag,
    [Radio.name]: Radio,
    [RadioGroup.name]: RadioGroup,
    [Badge.name]: Badge,
    [Uploader.name]: Uploader,
    ProductSelect,
    ButtonCenter,
    FieldTextarea,
    FieldUploader,
    FieldDivider,
  },
  data() {
    return {
      productListItemType: this.GLOBAL.listItemType.product,
      placeholder: {
        productDesc: '请输入商品描述',
        remark: '请填写备注',
      },
      buttonName: {
        toStorage: '拟入库',
        storage: '正式入库',
      },
      ifShowDetail: true,
      ifShowCategory: false,
      ifShowProductNum: false,
      ifShowProductSize: false,
      ifShowProductFitting: false,
      category: {
        selfPurchase: false,
        consignment: false,
      },
      productNumEditColumns: [
        { text: '1个' },
        { text: '2个' },
        { text: '3个' },
      ],
      productNumAddColumns: [
        { text: '1个' },
        { text: '2个', disabled: true },
        { text: '3个', disabled: true },
      ],
      sizePop: {
        sizeTitle: "尺寸",
        quickChooseItemList: [],
      },
      fillPop: {
        fillTitle: "配件",
        quickChooseItemList: [],
      },
      key: {
        prodAttachUploader: new Date().getTime()
      },
      product: {
        id: this.$route.params.id,
        productNo: '',
        productDesc: '',
        costPrice: '',
        salePrice: '',
        retailPrice: '',
        ifAddProductSize: false,
        productSize: [],
        ifAddProductFitting: false,
        productFitting: [],
        category: '',
        productNum: '',
        remark: '',
        productPictures: [],
        productPictureIds: [],
        attachmentPictures: [],
        attachmentPictureIds: [],
        attachPics: [],
        attachPicIds: [],
        attachVideos: [],
        attachVideoIds: [],
      },
    };
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      if (this.$route.params.id) {
        this.getProductDetail()
      } else {
        this.getProductCode()
      }
    },
    formatter(value) {
      if (value) {
        if (value < 1000000000) {
          return value.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,');
        } else {
          return ('' + Math.floor(value / 10)).replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g, '$1,');
        }
      } else {
        return ''
      }
    },
    chooseCategory(value) {
      if (value === 1) {
        this.category.selfPurchase = true
        this.category.consignment = false
        this.product.category = "自购"
      }
      if (value === 2) {
        this.category.selfPurchase = false
        this.category.consignment = true
        this.product.category = "寄卖"
        this.product.productNum = '1个'
        this.product.costPrice = 0
      }
      this.ifShowCategory = !this.ifShowCategory
    },
    productNumConfirm(value) {
      this.ifShowProductNum = !this.ifShowProductNum
      this.product.productNum = value.text
    },
    productSizeConfirm(value) {
      this.ifShowProductSize = !this.ifShowProductSize
      this.product.productSize = []
      this.product.productSize = value
    },
    productFittingConfirm(value) {
      this.ifShowProductFitting = !this.ifShowProductFitting
      this.product.productFitting = []
      this.product.productFitting = value
    },
    productFittingHandler() {
      this.ifShowProductFitting = !this.ifShowProductFitting
      if(!this.fillPop.quickChooseItemList || this.fillPop.quickChooseItemList.length === 0) {
        getUserAccesories().then(res => {
          const {State, Msg, Data} = res
          if (State) {
            for (let i = 0; i < Data.length; i++) {
              const {id, accessory_name} = Data[i]
              const fillObj = {title: accessory_name, isChoose: false, id: id}
              const productFittingArray = this.product.productFitting
              for (let j = 0; j < productFittingArray.length; j++) {
                if (String(accessory_name) === String(productFittingArray[j])) {
                  fillObj.isChoose = true
                }
              }
              this.fillPop.quickChooseItemList.push(fillObj)
            }
          } else { Toast(Msg) }
        })
      }

    },
    productSizeHandler() {
      this.ifShowProductSize = !this.ifShowProductSize
      if(!this.sizePop.quickChooseItemList || this.sizePop.quickChooseItemList.length === 0) {
        getUserSizes().then(res => {
          const {State, Msg, Data} = res
          if (State) {
            for (let i = 0; i < Data.length; i++) {
              const {id, size_name} = Data[i]
              const sizeObj = {title: size_name, isChoose: false, id: id}
              const productSizeArray = this.product.productSize
              for (let j = 0; j < productSizeArray.length; j++) {
                sizeObj.isChoose = String(size_name) === String(productSizeArray[j])
              }
              this.sizePop.quickChooseItemList.push(sizeObj)
            }
          } else { Toast(Msg) }
        })
      }
    },
    productSelectBack() {
      this.ifShowProductFitting = false
      this.ifShowProductSize = false
    },
    addProduct() {
      const productDescTextarea = this.$refs.productDescTextarea.desc
      const remarkTextarea = this.$refs.remarkTextarea.desc
      const prodPicIdList = this.$refs.prodPicUploaderRef.getProdPicIdList()
      const prodAttachIdList = this.product.attachmentPictureIds
      let params = {
        product_status: this.listItemCode === this.productListItemType.toStorage ? '拟入库' : '正式入库',
        product_code: this.product.productNo,
        product_category: this.product.category,
        product_cost_price: this.product.costPrice ? Number(this.product.costPrice.replaceAll(',', '')) : 0,
        product_sale_price: this.product.salePrice ? Number(this.product.salePrice.replaceAll(',', '')) : 0,
        product_retail_price: this.product.retailPrice ? Number(this.product.retailPrice.replaceAll(',', '')) : 0,
        // product_quantity: this.product.productNum ? parseInt(this.product.productNum.replace('个', '')) : 1,
        size: this.product.productSize ? this.product.productSize.join(',') : '',
        // accessories: this.product.productFitting ? this.product.productFitting.join(',') : '',
        product_description: productDescTextarea,
        note: remarkTextarea,
        product_image_list: prodPicIdList ? prodPicIdList.join(',') : '',
        product_watermark_list: prodPicIdList ? String(prodPicIdList[0]) : '',
        attachment: prodAttachIdList ? prodAttachIdList.join(',') : '',
      }
      if (!params.product_description) {
        Toast('请输入商品描述')
      } else if (!params.product_category) {
        Toast('请选择商品分类')
      } else {
        this.$loading.show()
        createProduct(params).then(res => {
          const {State} = res
          if (State) {
            this.$emit("productNumRefreshEvent")
            this.$router.push(this.GLOBAL.pathSetting.product.main)
          } else {
            Toast("新增失败")
          }
          this.$loading.close()
        }).catch(() => {this.$loading.close()})
      }
    },
    buttonStorage: function () {
      let params = {
        pathParam: this.product.id,
        product_status: "正式入库"
      }
      this.$loading.show()
      changeProductStatus(params).then(res => {
        const {State, Msg} = res
        if (State) {
          this.$emit("productNumRefreshEvent")
          this.$router.push({
            path: this.GLOBAL.pathSetting.product.main,
            query: {tab: this.listItemCode,},
          })
        } else { Toast(Msg) }
        this.$loading.close()
      }).catch(() => {this.$loading.close()})
    },
    editProduct() {
      const productDescTextarea = this.$refs.productDescTextarea.desc
      const remarkTextarea = this.$refs.remarkTextarea.desc
      const productImageList = this.$refs.prodPicUploaderRef.getProdPicIdList()
      const attachmentImageList = this.product.attachmentPictureIds
      let params = {
        pathParam: this.product.id,
        product_status: this.listItemCode === this.productListItemType.toStorage ? '拟入库' : '正式入库',
        id: this.product.id,
        product_code: this.product.productNo,
        product_category: this.product.category,
        product_cost_price: this.product.costPrice ? Number(this.product.costPrice.replaceAll(',', '')) : 0,
        product_sale_price: this.product.salePrice ? Number(this.product.salePrice.replaceAll(',', '')) : 0,
        product_retail_price: this.product.retailPrice ? Number(this.product.retailPrice.replaceAll(',', '')) : 0,
        // product_quantity: this.product.productNum ? this.product.productNum.replace('个', '') : 1,
        size: this.product.productSize ? this.product.productSize.join(',') : '',
        // accessories: this.product.productFitting ? this.product.productFitting.join(',') : '',
        product_description: productDescTextarea,
        note: remarkTextarea,
        product_image_list: productImageList ? productImageList.join(',') : '',
        product_watermark_list: productImageList ? String(productImageList[0]) : '',
        attachment: attachmentImageList ? attachmentImageList.join(',') : ''
      }
      if (!params.product_description) {
        Toast('请输入商品描述')
      } else if (!params.product_category) {
        Toast('请选择商品分类')
      } else {
        this.$loading.show()
        editProduct(params).then(res => {
          const {State, Msg} = res
          if (State) {
            this.$router.push({
              path: this.GLOBAL.pathSetting.product.main,
              query: {tab: this.listItemCode,},
            })
          } else { Toast(Msg) }
          this.$loading.close()
        }).catch(() => {this.$loading.close()})
      }
    },
    delProduct(productId) {
      this.$loading.show()
      deleteProduct({pathParam: Number(productId)}).then(res => {
        const {State, Msg} = res
        if (State) {
          this.$emit("productNumRefreshEvent")
          this.$router.push({
            path: this.GLOBAL.pathSetting.product.main,
            query: {tab: this.listItemCode,},
          })
        } else { Toast(Msg) }
        this.$loading.close()
      }).catch(() => {this.$loading.close()})
    },
    getProductCode() {
      getProductCode().then(res => {
        this.product.productNo = res
      })
    },
    getProductDetail() {
      viewProductDetail({pathParam: this.$route.params.id}).then(res => {
        const {State, Msg, Data} = res
        if (State) {
          const {
            product_code, product_description, product_category, size, note,
            product_cost_price, product_sale_price, product_retail_price, product_image_list, attachment
          } = Data
          this.product.productNo = product_code
          this.product.productDesc = product_description
          this.product.category = product_category
          this.product.productSize = size ? [size] : []
          // accessories.forEach(productFittingItem => {
          //   if (productFittingItem) {
          //     this.product.productFitting.push(productFittingItem)
          //   }
          // })
          // this.product.productNum = product_quantity
          this.product.remark = note
          this.product.costPrice = product_cost_price
          this.product.salePrice = product_sale_price
          this.product.retailPrice = product_retail_price
          if (product_image_list) {
            product_image_list.forEach(productImg => {
              const { id, cover_image, url } = productImg
              const type = this.$baseJS.getUrlType(url)
              const prodPicItem = { id:id, type: type, url: url, coverImage: cover_image }
              this.product.productPictures.push(prodPicItem)
              this.product.productPictureIds.push(id)
            })
          }
          if (attachment) {
            attachment.forEach(attachmentImg => {
              const { id, cover_image, url } = attachmentImg
              const type = this.$baseJS.getUrlType(url)
              const attachmentItem = { id: id, type: type, url: url, coverImage: cover_image }
              this.product.attachmentPictureIds.push(id)
              if (this.$baseJS.typeIsVideo(type)) {
                this.product.attachVideos.push(attachmentItem)
              } else {
                this.product.attachPics.push(attachmentItem)
              }
            })
            if (this.product.attachPics && this.product.attachPics.length > 0) {
              this.product.attachPics.forEach(attachPic => this.product.attachmentPictures.push(attachPic))
            }
            if (this.product.attachVideos && this.product.attachVideos.length > 0) {
              this.product.attachVideos.forEach(attachPic => this.product.attachmentPictures.push(attachPic))
            }
          }
          this.$refs.productDescTextarea.setValue(product_description)
          this.$refs.remarkTextarea.setValue(note)
          this.key.prodAttachUploader = new Date().getTime()
        } else { Toast(Msg) }
      })
    },
  },
};
</script>

<style scoped>

.collSpan-div {
  width: 375px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.collSpan-div > span {
  padding-top: 32px;
  padding-bottom: 16px;
}

.collSpan-div > img {
  padding-top: 32px;
  padding-bottom: 16px;
  padding-left: 4px;
}

.del-div {
  height: 86px;
  background: #f5f5f5;
  color: #C62400;
  display: flex;
  align-items: center;
  justify-content: center;
}

.field-cell {
  height: 54px;
  padding: 16px 0;
  color: #242424;
}
</style>
<style>
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  overflow: hidden;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
}
.mui-content {
  height: 100%;
  overflow: auto;
}
</style>
